﻿using AntdUI;
using CodeGenerator.Utils;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace CodeGenerator.Dialog
{
    public partial class OutputConfigDialog : Form
    {
        private Column[] PathTableHeaders = { new Column("Name", "配置名称", ColumnAlign.Center), new Column("Path", "生成路径", ColumnAlign.Left), new Column("Btns", "操作", ColumnAlign.Center) };
        AntList<PathTableRow> PathList = new AntList<PathTableRow>();
        ConfigUtil Config { get; } = new ConfigUtil(ConfigUtil.OutputPathFile);
        int _editing = 0;
        public string TemplateType
        {
            get
            {
                var type = "front";
                if (typeSegmented.SelectIndex == 1)
                {
                    type = "back";
                }
                return type;
            }
        }
        public string TemplateTypeName
        {
            get
            {
                var name = "前端";
                if (typeSegmented.SelectIndex == 1)
                {
                    name = "后端";
                }
                return name;
            }
        }
        public OutputConfigDialog()
        {
            //禁用大小可调整性
            this.FormBorderStyle = FormBorderStyle.FixedSingle;
            //禁用最大化按钮
            this.MaximizeBox = false;
            InitializeComponent();
        }

        private void OutputConfigDialog_Load(object sender, EventArgs e)
        {
            InitPathTable();
        }
        /// <summary>
        /// 初始化路径配置表
        /// </summary>
        private void InitPathTable()
        {
            pathTable.Columns = PathTableHeaders;
            PathTableHeaders[0].Width = "80";
            PathTableHeaders[2].Width = "120";
            PathList.Clear();
            foreach (var pathConfig in Config.GetConfigs())
            {
                if (pathConfig["Type"].ToString() == TemplateType)
                {
                    try
                    {
                        PathList.Add(new PathTableRow()
                        {
                            Id = int.Parse(pathConfig["id"].ToString()),
                            Name = pathConfig["Name"].ToString(),
                            Path = pathConfig["Path"].ToString(),
                            Type = TemplateType,
                        }); ;
                    }catch (Exception)
                    {

                    }
                }
            }
            pathTable.Binding(PathList);
        }
        private void OnRowSelectBtnClicked(int i, PathTableRow row)
        {
            var fsd = new FolderSelectDialog();
            fsd.Title = "请选择路径";
            var show = fsd.ShowDialog();
            if (!show) return;
            var path = fsd.FileName;
            var selectPath = path;
            row.Path = selectPath;
            row.IsEditing = true;
        }
        private void OnRowSaveBtnClicked(int i, PathTableRow row)
        {
            if (row.Name.IsNullOrEmpty())
            {
                throw new Exception("名称不能为空");
            }
            if (row.Path.IsNullOrEmpty())
            {
                throw new Exception("路径不能为空");
            }
            if (row.Id == null)
            {
                var json = Config.ToJsonObj(new { row.Name, row.Path, Type = TemplateType });
                row.Id = Config.AddConfig(json);
            }
            else
            {
                var json = Config.ToJsonObj(new { row.Name, row.Path, id = row.Id, row.Type });
                Config.UpdateConfig(json);
            }
            row.IsEditing = false;
        }
        private void OnRowDeleteBtnClicked(int i, PathTableRow row)
        {
            if (row.Id != null)
            {
                var result = AntdUI.Modal.open(new AntdUI.Modal.Config(this, "提示", "是否删除该路径？", TType.Warn)
                {
                    CancelText = "取消",
                    OkText = "确定"
                });
                if (result == DialogResult.OK)
                {
                    Config.RemoveConfigById((int)row.Id);
                }
                else
                {
                    return;
                }
            }
            PathList.RemoveAt(i);
        }
        private void addBtn_Click(object sender, EventArgs e)
        {
            var row = new PathTableRow()
            {
                Name = "",
                Path = "",
                Type = TemplateType,
            };
            PathList.Add(row);
        }

        private bool pathTable_CellBeginEdit(object sender, object value, object record, int rowIndex, int columnIndex)
        {
            var row = record as PathTableRow;
            row.IsEditing = true;
            return true;
        }

        private void pathTable_CellButtonClick(object sender, CellLink btn, MouseEventArgs args, object record, int rowIndex, int columnIndex)
        {
            switch (btn.Id)
            {
                case "select":
                    OnRowSelectBtnClicked(rowIndex - 1, record as PathTableRow);
                    break;
                case "save":
                    OnRowSaveBtnClicked(rowIndex - 1, record as PathTableRow);
                    break;
                case "delete":
                    OnRowDeleteBtnClicked(rowIndex - 1, record as PathTableRow);
                    break;
            }
        }

        private void typeSegmented_SelectIndexChanged(object sender, int value)
        {
            InitPathTable();
            addBtn.Text = "新增" + TemplateTypeName + "配置";
        }

    }
    class PathTableRow : NotifyProperty
    {
        public int? Id { set; get; }
        public string Name { get; set; }
        private string _path { get; set; }
        public string Path
        {
            get => _path;
            set
            {
                if (value.IsNotNullAndNotEmpty() && !Directory.Exists(value))
                {
                    OnPropertyChanged(nameof(Path));
                    throw new Exception($"{Name}的路径不存在");
                }
                _path = value;
                OnPropertyChanged(nameof(Path));
            }
        }
        public string Type { get; set; }
        bool _isEditing { get; set; } = false;
        public bool IsEditing
        {
            get => _isEditing;
            set
            {
                if (_isEditing == value) return;
                _isEditing = value;
                Btns[1].Enabled = value;
                OnPropertyChanged(nameof(Btns));
            }
        }
        public CellButton[] Btns { get; } = new CellButton[]
        {
            new CellButton("select","选择",TTypeMini.Primary),
            new CellButton("save","保存",TTypeMini.Primary){ Enabled = false},
            new CellButton("delete","删除",TTypeMini.Error)
        };

    }
}
